package com.gitee.limaozhi.socket.lesson03.example3;

import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 输入处理器
 *
 * @author hzlimaozhi
 * @date 2019/08/07 11:01
 */
public class InputHandler extends HandlerAdapter {

    /**
     * 发往下个处理器的请求数
     */
    private AtomicInteger req = new AtomicInteger(0);

    @Override
    public Handler start() {
        context().execute(() -> {
            try {
                byte[] buffer = new byte[1024];
                while (true) {
                    int count = context().getInputStream().read(buffer);
                    if (count == -1) {
                        break;
                    }
                    if (count > 0) {
                        byte[] bytes = new byte[count];
                        System.arraycopy(buffer, 0, bytes, 0, count);
                        next().handle(bytes);
                        req.incrementAndGet();
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                context().shutdownInput();
//                context().print(context().getName() + "：Input：" + req.get());
                next().finish(req.get());
//                context().print(context().getName() + "：Input：线程退出");
            }
        });
        return next().start();
    }

}
